package Thread;

public class WaitExample {
    public static void main(String[] args) {
        final Object lock = new Object();

        Thread thread = new Thread(() -> {
            synchronized (lock) {
                try {
                    System.out.println("线程准备等待2秒");
                    lock.wait(2000); // 让线程等待2秒钟，超时后自动唤醒
                    System.out.println("线程结束等待");
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start(); // 新线程启动后才能调用wait，否则会导致IllegalMonitorStateException

        synchronized (lock) {
            try {
                System.out.println("主线程准备等待2秒");
                lock.wait(2000); // 在同步块内调用wait
                System.out.println("主线程结束等待");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        synchronized (lock) {
            lock.notify();
        }

    }
}
